package com.centaline.androidsalesblog.notification;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.NotificationCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.MainActivity;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.model.businissobject.RongUserInfoBo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centaline.androidsalesblog.widgets.CropCircleTransformation;
import com.centanet.framework.utils.SprfUtil;
import com.orhanobut.logger.Logger;

import java.util.Locale;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.TextMessage;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 聊天通知
 * Created by guilin on 16/4/7.
 */
public class RongNotification {

    private final Context context;
    private final NotificationCompat.Builder builder;
    private final NotificationManagerCompat managerCompat;

    private int notificationId;
    private SimpleTarget<Bitmap> simpleTarget = new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
            builder.setLargeIcon(new CropCircleTransformation(context)
                    .transform(BitmapResource.obtain(resource, Glide.get(context).getBitmapPool()), 200, 200)
                    .get());
            update();
        }
    };

    public RongNotification(Context context) {
        this.context = context;
        builder = new NotificationCompat.Builder(context);
        builder.setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setSmallIcon(R.mipmap.notification_app)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setAutoCancel(true)
                .setOngoing(false)
                .build();
        managerCompat = NotificationManagerCompat.from(context);
    }

    /**
     * 通知
     */
    public void notification(final Message message) {
        if (message != null) {
            String targetId = message.getTargetId();
            notificationId = targetId.hashCode();
            if (RongIMClient.getInstance() != null) {//获取未读消息数量
                RongIMClient.getInstance().getUnreadCount(Conversation.ConversationType.PRIVATE,
                        targetId,
                        new RongIMClient.ResultCallback<Integer>() {
                            @Override
                            public void onSuccess(Integer integer) {
                                notifyMessage(message, integer > 0 ? integer : 1);
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {
                                notifyMessage(message, 1);
                            }
                        });
            }
        }
    }

    /**
     * 通知文本信息
     */
    private void notifyMessage(Message message, int count) {
        builder.setContentInfo(String.format(Locale.CHINA, "%d条未读", count));
        MessageContent messageContent = message.getContent();
        if (messageContent != null) {
            if (messageContent instanceof TextMessage) {//文本消息
                TextMessage textMessage = (TextMessage) messageContent;
                builder.setContentText(textMessage.getContent());
            } else {//图片消息
                builder.setContentText("[图片]");
            }
        }
        String targetId = message.getTargetId();
        boolean mainActivityOpen = SprfUtil.getBoolean(context, SprfConstant.MAIN_ACTIVITY_OPEN, false);
        Logger.d("mainActivityOpen : %b", mainActivityOpen);
        Intent[] intents = new Intent[mainActivityOpen ? 1 : 2];
        if (mainActivityOpen) {
            intents[0] = new Intent(context, ChatActivity.class);
            intents[0].putExtra(ExtraConstant.TargetId, targetId);
        } else {
            intents[0] = new Intent(context, MainActivity.class);
            intents[1] = new Intent(context, ChatActivity.class);
            intents[1].putExtra(ExtraConstant.TargetId, targetId);
        }
        builder.setContentIntent(PendingIntent.getActivities(context, notificationId, intents, PendingIntent.FLAG_CANCEL_CURRENT));
        builder.setWhen(System.currentTimeMillis());
        update();
        targetUserInfo(targetId);
    }

    /**
     * 更新
     */
    private void update() {
        managerCompat.notify(CommonConstant.TAG_NOTIFICATION_IM, notificationId, builder.build());
    }

    /**
     * 聊天用户信息
     */
    private void targetUserInfo(String targetId) {
        Observable.concat(RxDataBase.rongUserInfo(targetId)
                        .subscribeOn(Schedulers.io()),
                RxRequest.rongUserInfo(ChatActivity.class, targetId)
                        .map(new Func1<StaffDo, RongUserInfoBo>() {
                            @Override
                            public RongUserInfoBo call(StaffDo staffDo) {
                                saveTargetStaff(staffDo);
                                if (staffDo == null) {
                                    return null;
                                } else {
                                    return new RongUserInfoBo(RongUserIdUtil.getSatffId(staffDo.getStaffNo()),
                                            staffDo.getCnName(),
                                            staffDo.getImgUrl(),
                                            staffDo.getMobile());
                                }
                            }
                        }))
                .first()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<RongUserInfoBo>() {
                    @Override
                    public void call(RongUserInfoBo rongUserInfoBo) {
                        if (rongUserInfoBo != null) {
                            largeIcon(rongUserInfoBo.getPortraitUrl());
                            builder.setContentTitle(rongUserInfoBo.getNickName());
                            update();
                        }
                    }
                });
    }

    private void largeIcon(String url) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .error(R.drawable.ic_staff_default)
                .placeholder(R.drawable.ic_staff_default)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(200, 200)
                .into(simpleTarget);
    }

    /**
     * 保存聊天用户信息
     */
    private void saveTargetStaff(StaffDo staffDo) {
        RxDataBase.saveStaff(staffDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
    }
}
